package com.bobo.encryption.symmetric;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

/**
 * Java实现对称加密（AES）
 * 
 * 加密级别 DES<3DES<AES<PBE
 * @author win7
 *
 */
public class AEStest {

	public static String bobo="www.baobao.com";
	
	public static void main(String[] args) {
          JdkAES();
	}

	public static void JdkAES(){
		try {
			//1.初始化key秘钥	
				KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
				keyGenerator.init(new SecureRandom());//初始化一个key秘钥长度
				SecretKey secretkey= keyGenerator.generateKey();
				byte[] bytesecrekey= secretkey.getEncoded();
				//key秘钥转换
				Key key=new SecretKeySpec(bytesecrekey, "AES");
			//加密
				Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
				cipher.init(Cipher.ENCRYPT_MODE, key);
				byte[] result= cipher.doFinal(bobo.getBytes());
				System.out.println("jdk aes 加密："+HexBin.encode(result));
			
			//解密
				cipher.init(Cipher.DECRYPT_MODE, key);
				result= cipher.doFinal(result);
				System.out.println("jdk aes 解密："+new String(result));
				
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
